const path = require('path')
const multer  = require('multer')
const mime  = require('mime')

// 定义文件存储路径和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../public/uploads'))
  },
  filename: function (req, file, cb) {
    const ext = mime.getExtension(file.mimetype);
    const filename = `${file.fieldname}-${Date.now()}.${ext}`
    cb(null, filename)
  }
})

// 限制上传文件一些数据大小
const limits = {
  fileSize: 200 * 1000, // 200kb
  files: 1,
}

// 过滤器
const fileFilter = (req, file, cb) => {
  // 这个函数应该调用 `cb` 用boolean值来
  // 指示是否应接受该文件

  // 接受的文件类型
  const accessTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']

  if (!accessTypes.includes(file.mimetype)) {
    cb(new Error('文件类型必须是 .png、.jpg、.gif'))
  } else {
    // 接受这个文件，使用`true`
    cb(null, true)
  }
}

const uploadSingle = multer({
  storage,
  limits,
  fileFilter
}).single('file')

const uploadMiddleware = (req, res, next) => {
  uploadSingle(req, res, (err) => {
    res.set('Content-Type', 'application/json; charset=utf-8')
    if (err instanceof multer.MulterError) {
      // 发生 MulterError 错误
      console.log('MulterError', err.message);
      if (err.message.includes('File too large')) {
        res.send({
          code: 10000,
          message: `文件太大，超过${limits.fileSize / 1000} kb啦`
        })
      } else {
        res.send({
          code: 10000,
          message: err.message
        })
      }
    } else if (err) {
      // 发生 js Error 错误
      res.send({
        code: 10000,
        message: err.message
      })
    }
    // 一切都好
    next()
  })
}

module.exports = uploadMiddleware
